package com.qeeyou.apps.android.craftsman.activity.home;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;

import com.qeeyou.apps.android.craftsman.R;
import com.qeeyou.apps.android.craftsman.adapter.MasterAdapter;
import com.qeeyou.apps.android.craftsman.adapter.PopWindowListAdapter;
import com.qeeyou.apps.android.craftsman.common.Contants;
import com.qeeyou.apps.android.craftsman.po.MasterInfo;
import com.qeeyou.apps.android.craftsman.service.AppService;
import com.qeeyou.apps.android.craftsman.view.CustomLoadingDialog;
import com.qeeyou.apps.android.craftsman.view.DropdownButton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CraftsmanActivity extends Activity {

    private ImageView btnBack;
    private DropdownButton btnAll;
    private DropdownButton btnGrade;
    private DropdownButton btnDistance;
    private ListView lstvCraftsman;
    private MasterAdapter mAdapter;
    private List<MasterInfo> craftsmanList;
    private String pageNo;                          //页码
    private String pageSize;                        //每页数目
    private String sortType;                        //排序
    private String coordinates;                     //经纬度
    private CustomLoadingDialog mLoadingDialog;
    private PopupWindow mPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_craftsman);

        setView();
        setEvent();

        //TODO -- 初始化
        btnAll.setSelected(true);
        btnGrade.setSelected(false);
        btnDistance.setSelected(false);
        sortType = Contants.SORT_BY_DEFAULT;
        loadData(sortType);
    }

    private void setView() {
        btnBack = (ImageView) this.findViewById(R.id.btnBack4Craftsman);
        btnAll = (DropdownButton) this.findViewById(R.id.btnAll4Craftsman);
        btnGrade = (DropdownButton) this.findViewById(R.id.btnGrade4Craftsman);
        btnDistance = (DropdownButton) this.findViewById(R.id.btnDistance4Craftsman);
        lstvCraftsman = (ListView) this.findViewById(R.id.lstvCraftsman4Craftsman);
    }

    private void setEvent() {
        mAdapter = new MasterAdapter(CraftsmanActivity.this, craftsmanList);
        lstvCraftsman.setAdapter(mAdapter);
        lstvCraftsman.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //TODO -- 跳转到师傅详情界面
                MasterInfo masterInfo = mAdapter.getItem(i);
                if(masterInfo != null) {
                    Intent intent = new Intent(CraftsmanActivity.this, MasterDetailActivity.class);
                    intent.putExtra("masterInfo", masterInfo);
                    CraftsmanActivity.this.startActivity(intent);
                }
            }
        });

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CraftsmanActivity.this.finish();
            }
        });

        btnAll.setOnClickListener(onSortClickListener);
        btnGrade.setOnClickListener(onSortClickListener);
        btnDistance.setOnClickListener(onSortClickListener);
    }

    private View.OnClickListener onSortClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            btnAll.setSelected(false);
            btnGrade.setSelected(false);
            btnDistance.setSelected(false);
            String sortType = Contants.SORT_BY_DEFAULT;
            if(view == btnAll) {
                btnAll.setSelected(true);
                sortType = Contants.SORT_BY_DEFAULT;
                //TODO -- 显示下来列表
//                showPopWindow();
            } else if(view == btnGrade) {
                btnGrade.setSelected(true);
                sortType = Contants.SORT_BY_SCORE;
                if(mPopupWindow != null) {
                    mPopupWindow.dismiss();
                }
            } else {
                btnDistance.setSelected(true);
                sortType = Contants.SORT_BY_DISTANCE;
                if(mPopupWindow != null) {
                    mPopupWindow.dismiss();
                }
            }
            loadData(sortType);
        }
    };

    private void showPopWindow() {
        WindowManager manager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(metrics);
        int width = metrics.widthPixels;         // 屏幕宽度（像素）
        int height = metrics.heightPixels;
        View contentView = LayoutInflater.from(CraftsmanActivity.this).inflate(R.layout.view_pop_window_list, null, false);
        if(mPopupWindow == null) {
            mPopupWindow = new PopupWindow(contentView, width, height / 4);
        }
        mPopupWindow.setOutsideTouchable(false);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        ListView lstvItems = (ListView) contentView.findViewById(R.id.lstvItem4Sort);
        List<String> itemArray = new ArrayList<String>();
        itemArray.add("综合排序");
        itemArray.add("按浏览量");
        itemArray.add("按服务次数");
        final PopWindowListAdapter adapter = new PopWindowListAdapter(CraftsmanActivity.this, itemArray);
        lstvItems.setAdapter(adapter);
        lstvItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String titleStr = (String) adapter.getItem(position);
                btnAll.setText(titleStr);
                //TODO -- 排序
                mPopupWindow.dismiss();
            }
        });
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                mPopupWindow = null;
            }
        });
        mPopupWindow.showAsDropDown(btnAll, 0, 20);
    }

    private void loadData(String sortType) {
        this.sortType = sortType;
        this.pageNo = "0";
        this.pageSize = "20";
        this.coordinates = "121.402440,31.168146";
        String[] params = {this.pageNo, this.pageSize, this.sortType, this.coordinates};
        new GetCraftsmanList().execute(params);
    }

    class GetCraftsmanList extends AsyncTask<String, Void, List<MasterInfo>> {

        public GetCraftsmanList() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if(mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(CraftsmanActivity.this);
            }
            mLoadingDialog.setMessage("正在获取师傅列表...");
            mLoadingDialog.show();
        }

        @Override
        protected List<MasterInfo> doInBackground(String... params) {
            String pageNo = params[0];
            String pageSize = params[1];
            String sortType = params[2];
            String mycoo = params[3];
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("pageIndex", pageNo);
            paramMap.put("pageSize", pageSize);
            paramMap.put("param", sortType);
            paramMap.put("mycoo", mycoo);
            List<MasterInfo> masterList = AppService.getInstance().getMasterList(paramMap);
            return masterList;
        }

        @Override
        protected void onPostExecute(List<MasterInfo> masterList) {
            super.onPostExecute(masterList);
            if(mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if(masterList != null && masterList.size() > 0) {
                mAdapter.setItems(masterList);
            }
        }
    }
}
